package com.example.demo.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class ExcelTemplateGenerator {
    
    public static void generateUserImportTemplate() {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户导入模板");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            List<String> headers = Arrays.asList("姓名", "邮箱", "电话", "地址");
            
            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            // 写入标题
            for (int i = 0; i < headers.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers.get(i));
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 20 * 256); // 设置列宽
            }
            
            // 添加示例数据
            Object[][] data = {
                {"张三", "zhangsan@qq.com", "13800138001", "北京市朝阳区"},
                {"李四", "lisi@qq.com", "13800138002", "上海市浦东新区"},
                {"王五", "wangwu@qq.com", "13800138003", "广州市天河区"}
            };
            
            // 写入示例数据
            for (int i = 0; i < data.length; i++) {
                Row row = sheet.createRow(i + 1);
                for (int j = 0; j < data[i].length; j++) {
                    row.createCell(j).setCellValue((String) data[i][j]);
                }
            }
            
            // 获取resources目录的路径
            Resource resource = new ClassPathResource("");
            String resourcesPath = resource.getFile().getAbsolutePath();
            String templatePath = resourcesPath + File.separator + "templates" + File.separator + "用户导入模板.xlsx";
            
            // 确保目录存在
            File templateDir = new File(resourcesPath + File.separator + "templates");
            if (!templateDir.exists()) {
                templateDir.mkdirs();
            }
            
            // 保存文件
            try (FileOutputStream fileOut = new FileOutputStream(templatePath)) {
                workbook.write(fileOut);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        generateUserImportTemplate();
    }
} 